package com.mc.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class WebUtil {

	private WebUtil() {
		super();
	}

	private static final ThreadLocal<HttpServletRequest> THREAD_LOCAL = new ThreadLocal<HttpServletRequest>();

	public static HttpServletRequest getRequest() {
		//HttpServletRequest request = (HttpServletRequest) THREAD_LOCAL.get();
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		return request;
	}

	public static HttpServletResponse getResponse() {
		//HttpServletRequest request = (HttpServletRequest) THREAD_LOCAL.get();
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletResponse response = attributes.getResponse();
		return response;
	}

	public static String getWebRoot() {
		return getRequest().getSession().getServletContext().getRealPath("/");
	}

	public static String getWebPath(String path) {
		return getRequest().getServletContext().getRealPath(path);
	}

	public static String getWebContextPath() {
		HttpServletRequest request = getRequest();
		return request.getContextPath();
	}

	public static void setRequest(HttpServletRequest request) {
		THREAD_LOCAL.set(request);
	}

	public static void r404(HttpServletResponse response) {
		try {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		} catch (IOException e) {
		}
	}

	public static Object session(String name) {
		return WebUtil.getRequest().getSession().getAttribute(name);
	}

	public static <T> T getBean(HttpServletRequest request, Class<T> clazz) {
		return WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(clazz);
	}

	public static Object getBean(HttpServletRequest request, String serviceid) {
		return WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(serviceid);
	}

	public static void session(String name, Object val) {
		WebUtil.getRequest().getSession().setAttribute(name, val);
	}

	public static void removeSession(String name) {
		WebUtil.getRequest().getSession().removeAttribute(name);
	}

	public static void writer(HttpServletResponse response, String str) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(str);
		response.flushBuffer();
	}

	public static <T> ResponseEntity<T> getResponseEntity(T t) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		return new ResponseEntity<T>(t, headers, HttpStatus.OK);
	}

	public static String getInputStreamParam(HttpServletRequest request, String name) {
		String order = request.getParameter(name);
		if (StringUtils.isNotBlank(order)) {
			return order;
		}
		try {
			InputStreamReader is = new InputStreamReader(request.getInputStream(), "UTF-8");
			char[] bf = new char[888];
			StringBuilder buffer = new StringBuilder();
			int i;
			while ((i = is.read(bf)) != -1) {
				buffer.append(bf, 0, i);
			}
			return buffer.toString();
			// return IOUtils.toString(request.getInputStream(), "UTF-8");
		} catch (IOException e) {
		}
		return null;
	}

	/**
	 * 获取ip地址
	 * @return
	 */
	public static String getRemoteIP(HttpServletRequest request) throws Exception{

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
				String ipLeval = ip.substring(ip.indexOf(",") + 1, ip.length());
				while ("unknown".equals(ip)) {
					if (ip.indexOf(",") > 0) {
						ip = ipLeval.substring(0, ipLeval.indexOf(","));
					} else {
						ip = ipLeval;
						break;
					}
				}
			}
		}
		return ip;
	}

	public static void writeContent(String content) throws IOException {
		HttpServletResponse response = WebUtil.getResponse();
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "application/json;charset=UTF-8");
		response.setHeader("icop-content-type", "com/xinyang/common/exception");

		PrintWriter writer = null;
		writer = response.getWriter();
		writer.print(JSONObject.toJSONString(content));
		writer.flush();
		writer.close();
	}


}
